package org.ysling.litemall.core.service;
// Copyright (c) [ysling] [927069313@qq.com]
// [litemall-plus] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//             http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ysling.litemall.core.express.ExpressService;
import org.ysling.litemall.core.wxpay.WxProperties;
import org.ysling.litemall.db.domain.LitemallOrder;
import org.ysling.litemall.db.domain.LitemallOrderGoods;
import org.ysling.litemall.db.util.OrderConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;

@Service
public class SubscribeMessageService {

    private final Log logger = LogFactory.getLog(SubscribeMessageService.class);
    /**消息订阅请求地址*/
    private final static String  tokenPath = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    /**消息订阅请求地址*/
    private final static String  postPath = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";
    /**发货订阅模板id*/
    private final static String  shipTmplId = "g8tMdyhgzWlxPP-wFfbiwaSSmMO7Ga0feq71E29M8_I";
    /**退款订阅模板id*/
    private final static String  refundTmplId = "em0NVJsdJ1emUPf3U5ScMZ4SDp4Pi0kh5kSUtix1hu4";
    /**新订单订阅模板id*/
    private final static String  newOrderTmplId = "Vhyn0wCT_H7TK3TbxHoedWO3-3f87kchHCV5blSv5EI";



    @Autowired
    private WxProperties properties;
    @Autowired
    private ExpressService expressService;
    //声明需要格式化的格式(日期加时间)
    private DateTimeFormatter dfDateTime = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm");

    public String getAccessToken() {
        String appId = properties.getAppId();
        String appSecret = properties.getAppSecret();
        String url = tokenPath + "&appid=" + appId + "&secret=" + appSecret;
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.getStr("access_token");
    }


    /**
     * 订单发货订阅
     * @param openId
     * @param order
     */
    public void shipSubscribe(String openId ,LitemallOrder order){
        JSONObject body = new JSONObject();
        body.set("touser",openId);
        body.set("template_id",shipTmplId);
        //拼接模板json
        JSONObject json=new JSONObject();
        json.set("character_string1",new JSONObject().set("value",order.getOrderSn()));
        json.set("date3",new JSONObject().set("value", dfDateTime.format(order.getShipTime())));
        json.set("thing7",new JSONObject().set("value",expressService.getVendorName(order.getShipChannel())));
        json.set("character_string9",new JSONObject().set("value", order.getShipSn()));
        json.set("thing15",new JSONObject().set("value", order.getAddress()));
        body.set("data",json);
        //发送
        String accessToken= getAccessToken();
        String result = HttpUtil.post(postPath + "?access_token=" + accessToken, body.toString());
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (!jsonObject.getStr("errcode").equals("0")){
            logger.info("消息订阅错误信息-------发货订阅-----错误信息：" + result);
        }
    }


    /**
     * 订单退货审核订阅通知
     * @param openId
     * @param order
     */
    public void refundSubscribe(String openId ,LitemallOrder order){
        JSONObject body = new JSONObject();
        body.set("touser",openId);
        body.set("template_id",refundTmplId);
        //拼接模板json
        JSONObject json=new JSONObject();
        json.set("thing1",new JSONObject().set("value", OrderConstant.orderStatusText(order)));
        json.set("character_string2",new JSONObject().set("value", order.getOrderSn()));
        json.set("amount3",new JSONObject().set("value",order.getRefundAmount()));
        json.set("time11",new JSONObject().set("value", dfDateTime.format(order.getPayTime())));
        json.set("date4",new JSONObject().set("value", dfDateTime.format(order.getRefundTime())));
        body.set("data",json);
        //发送
        String accessToken= getAccessToken();
        String result = HttpUtil.post(postPath + "?access_token=" + accessToken, body.toString());
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (!jsonObject.getStr("errcode").equals("0")){
            logger.info("消息订阅错误信息-------退款订阅-----错误信息：" + result);
        }
    }

    /**
     * 新订单审核订阅通知
     * @param openId
     * @param order
     */
    public void newOrderSubscribe(String openId ,LitemallOrder order , LitemallOrderGoods orderGoods){
        JSONObject body = new JSONObject();
        body.set("touser",openId);
        body.set("template_id",newOrderTmplId);
        //拼接模板json
        JSONObject json=new JSONObject();
        json.set("character_string1",new JSONObject().set("value", order.getOrderSn()));
        json.set("phrase2",new JSONObject().set("value", OrderConstant.orderStatusText(order)));
        json.set("thing4",new JSONObject().set("value", orderGoods.getGoodsName()));
        json.set("thing10",new JSONObject().set("value", order.getAddress()));
        json.set("thing8",new JSONObject().set("value", "请12小时内及时发货"));
        body.set("data",json);
        //发送
        String accessToken= getAccessToken();
        String result = HttpUtil.post(postPath + "?access_token=" + accessToken, body.toString());
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (!jsonObject.getStr("errcode").equals("0")){
            logger.info("消息订阅错误信息-------新订单订阅-----错误信息：" + result);
        }
    }

}
